<template>
    <div class="main-content">
        <ElForm
            ref="searchFormRef"
            :model="searchForm"
            inline
            class="search-form"
            label-width="68px"
            label-position="left">
            <ElFormItem label="状态" prop="status">
                <ElSelect
                    v-model="searchForm.status"
                    size="default"
                    placeholder="请选择"
                >
                    <ElOption
                        v-for="item in statusOps"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></ElOption>
                </ElSelect>
            </ElFormItem>

            <ElFormItem label="道路编号" prop="code">
                <ElInput
                    v-model="searchForm.code"
                    size="default"
                    placeholder="请输入"
                ></ElInput>
            </ElFormItem>
            <ElFormItem label="道路名称" prop="name">
                <ElInput
                    v-model="searchForm.name"
                    size="default"
                    placeholder="请输入"
                ></ElInput>
            </ElFormItem>
            <ElFormItem label="项目" prop="projectId">
                <ElSelect
                    v-model="searchForm.projectId"
                    size="default"
                    filterable
                    placeholder="请选择"
                >
                    <ElOption
                        v-for="item in projectList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></ElOption>
                </ElSelect>
            </ElFormItem>


            <ElFormItem>
                <ElButton
                    size="default"
                    color="#4371EE"
                    @click="reset(false)"
                >
                    查询
                </ElButton>
                <ElButton
                    size="default"
                    plain=""
                    @click="reset(true)"
                >
                    重置
                </ElButton>
            </ElFormItem>
        </ElForm>
            <!-- </ElCol> -->
            <div class="btns">
                <ElButton

                    class="add-btn"
                    color="#4371EE"
                    size="default"
                    :icon="Plus"
                    v-permission="10"
                    @click="addShow = true"
                >
                    创建道路
                </ElButton>
            </div>
            <ElTable
                border
                id="userTable"
                class="table"
                :data="tableData"
                :style="{ height: `${maxTableHeight}px`, overflow: 'auto' }"
            >
                <ElTableColumn prop="code" label="道路编号" width="120px" />
                <ElTableColumn prop="name" label="道路名称" width="120px" />
                <ElTableColumn prop="status" label="状态" width="120px" >
                    <template #default="scope">
                        {{  statusOps.find(({ value }) => value == scope.row.status).label }}
                    </template>
                </ElTableColumn>
                <ElTableColumn prop="pipeLineTotal" label="管线总数" width="120px" />
                <ElTableColumn prop="pipeLineOverCount" label="管线完成数" width="120px" />
                <ElTableColumn prop="pipePointTotal" label="管井总数" width="120px" />

                <ElTableColumn prop="pipePointOverCount" label="管井完成数" width="120px" />
                <ElTableColumn  fixed="right" label="操作" width="500px">
                    <template #default="scope">

                        <Upload
                             accept=".dwg,.DWG"
                            v-permission="6"
                            class="upload-demo"

                            @success="(...e) => handleFileUpload(scope.row, 1, ...e)"
                        >
                        <ElButton
                            link
                            type="text"
                            size="default"

                            >
                            导入CAD
                            </ElButton>
                        </Upload>

                        <ElButton   v-permission="7" :disabled="!scope.row.cadFileUrl"  link type="text" size="default" @click="handleExport(scope.row.cadFileUrl)">
                            导出CAD
                        </ElButton>
                        <ElButton    v-permission="9" :disabled="!scope.row.reportFileUrl" link type="text" size="default" @click="handleExport(scope.row.reportFileUrl)">
                            导出报告
                        </ElButton>
                        <Upload
                            accept=".doc,.DOC,.docx,.DOCX,.pdf,.PDF,.csv,.excel,.xls,XLS,.XLSX,.xlsx,.CSV,.EXCEL"
                            v-permission="8"
                            class="upload-demo"
                            @success="(...e) => handleFileUpload(scope.row, 2, ...e)"
                        >
                            <ElButton    link type="text" size="default" >
                                导入报告
                            </ElButton>
                        </Upload>
                        <ElButton   v-permission="61"  link type="text" size="default" @click="handleExportInspect(scope.row)">
                            导出检测数据
                        </ElButton>
                        <ElButton   v-permission="10" link type="text" size="default" @click="editFun(scope.row)">
                        编辑
                        </ElButton>
                        <ElButton  v-permission="56"  link type="text" size="default" @click="handleDelete(scope.row)">
                        删除
                        </ElButton>
                    </template>
                </ElTableColumn>
            </ElTable>

            <ElPagination
                class="pagination"
                background
                layout="total,sizes,prev, pager, next,jumper"
                :total="total"
                :current-page="searchForm.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="searchForm.pageSize"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />

            <!--新增或编辑角色-->
            <ElDialog   class="main-dialog" v-model="addShow"  :title="addForm.id ? '编辑道路' : '创建道路'" width="480px">
                <div class="dialog-form">
                    <ElForm
                        ref="addFormRef"
                        :model="addForm"
                        :rules="rules"
                        label-width="80px"
                        label-position="left"
                    >
                        <ElFormItem label="道路编号" prop="code">
                            <el-input v-model="addForm.code" size="default" placeholder="请输入道路编号"  />
                        </ElFormItem>
                        <ElFormItem label="道路名称" prop="name">
                            <el-input v-model="addForm.name" size="default" placeholder="请输入道路名称" />
                        </ElFormItem>

                        <ElFormItem label="所属项目">
                            <ElSelect
                                v-model="addForm.projectId"
                                size="default"
                                placeholder="请选择"
                            >
                                <ElOption
                                    v-for="item in projectList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                ></ElOption>
                            </ElSelect>
                        </ElFormItem>
                    </ElForm>
                </div>
                <template #footer>
                    <span  class="dialog-footer">
                        <ElButton size="default" @click="addShow = false">取 消</ElButton>
                        <ElButton color="#4371EE" size="default" @click="submitForm(addFormRef)">提 交</ElButton>
                    </span>
                </template>

            </ElDialog>



             <!--新增或编辑角色-->
             <ElDialog   class="main-dialog" v-model="addInspectShow"  title="导出检测数据" width="480px">
                <div class="dialog-form">
                    <ElForm
                        ref="addFormRef"
                        :model="addInspectData"
                        :rules="rules"
                        label-width="80px"
                        label-position="left"
                    >
                        <ElFormItem label="道路编号" prop="code">
                            <el-input disabled v-model="addInspectData.code" size="default" placeholder="请输入道路编号"  />
                        </ElFormItem>
                        <ElFormItem label="道路名称" prop="name">
                            <el-input disabled v-model="addInspectData.name" size="default" placeholder="请输入道路名称" />
                        </ElFormItem>

                        <ElFormItem label="数据类型" prop="dataType">
                            <ElSelect
                                v-model="addInspectData.dataType"
                                size="default"
                                placeholder="请选择"
                            >
                                <ElOption
                                    label="管井"
                                    :value="1"
                                ></ElOption>
                                <ElOption
                                    label="管线"
                                    :value="2"
                                ></ElOption>
                            </ElSelect>
                        </ElFormItem>
                    </ElForm>
                </div>
                <template #footer>
                    <span  class="dialog-footer">
                        <ElButton size="default" @click="addInspectShow = false">取 消</ElButton>
                        <ElButton color="#4371EE" size="default" @click="submitInspectForm(addFormRef)">提 交</ElButton>
                    </span>
                </template>

            </ElDialog>



    </div>
</template>

<script setup lang="ts">
import useTableSetting from '@/hooks/useTableSetting';
import { ref, onMounted, reactive, nextTick, watch } from 'vue';

import { getRoadList, addRoad, editRoad, deleteRoad, getLoginUserProjects, importRoadFile, exportInspectData } from '@/api/index';
import { ElMessage, ElTree, FormInstance, ElMessageBox, ElLoading } from 'element-plus';

import { getFlatDeepTreeData } from '@/utils/common';
import { Search, Plus } from '@element-plus/icons-vue';
import { validateForm } from '@/helper/index';

const statusOps = [
    { label: '进行中', value: 0 },
    { label: '已完成', value: 1 }
];

const tableData: any = ref([]);

const projectList = ref([]);

const getProject = async () => {
    const list = await getLoginUserProjects();
    if(list && list.length) {
        projectList.value = list;
        searchForm.projectId = list[0].id;
    }
};

getProject();


const handleExport = async (url) => {
    const elink = document.createElement('a');
    elink.style.display = 'none';
    elink.href = url;
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink);

}


const searchFormRef = ref<FormInstance>(null);

const details = ref({});


const handleDelete = async (row) => {
    await ElMessageBox.confirm('确认要删除吗？', '提示', {
        confirmButtonText: '确  定',
        cancelButtonText: '取  消',
        type: 'warning'
    });
    await deleteRoad({ id: row.id});
    ElMessage.success('删除成功！');
    reset();
};



const searchForm = reactive<searchFormType>({
    'code': '',
    'name': '',
    'projectId': '',
    'status': '',
    pageNum: 1,
    pageSize: 20,
});
const total = ref<number>(0);


const rules = reactive({
    roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
    dataType: [{ required: true, message: '请选择数据类型', trigger: 'change' }],
});


const getList = async () => {
    try {
        const res: any = await getRoadList(searchForm);
        tableData.value = res.list;

        total.value = res.total;
    } catch (err) {}
};

const goDetail = (row) => {
    details.value = JSON.parse(JSON.stringify(row));
};

const reset = (reset) => {
    if(reset) {
        searchFormRef.value.resetFields();
        searchForm.projectId = projectList.value[0].id;
    }
    searchForm.pageNum = 1;
    getList();
};

const handleSizeChange = (rows: number) => {
    searchForm.pageNum = 1;
    searchForm.pageSize = rows;
    getList();
};
const handleCurrentChange = (page: number) => {
    searchForm.pageNum = page;
    getList();
};


const addShow = ref<boolean>(false);
const addFormRef = ref<FormInstance>(null);
const addForm = reactive<addRoleType>({
    id: '',
    code: '',
    name: '',
    projectId: '',

});

const resetForm = (form) => {
    Object.keys(form).forEach(key => addForm[key] = '');
};

watch(
    addShow,
    val => {
        if(!val) {
            addFormRef.value.clearValidate();
            resetForm(addForm);
        }
    }
);

const submitForm = async (formEl: FormInstance | undefined) => {
    await validateForm(formEl);

    addForm.id ? await editRoad(addForm) : await addRoad(addForm);
    ElMessage.success('提交成功！');
    addShow.value = false;
    getList();
};



const editFun = async (row: any) => {
    addShow.value = true;
    Object.keys(row).forEach(key => {
        if(key in addForm) {
            addForm[key] = row[key];
        }
    });
};


const handleFileUpload = async (row, fileType, fileDesc, fileUrl) => {
    const  params = {
        fileType,
        id: row.id,
        fileUrl,
        fileDesc
    }
    console.log(row, fileType, name, fileUrl)
    await importRoadFile(params)
    ElMessage.success('导入成功！');
    getList()
}
const addInspectShow = ref(false)
const addInspectData = ref({})

const handleExportInspect = async (row: any) => {
    addInspectShow.value = true
    let temp =JSON.parse(JSON.stringify(row));
    temp.dataType = null
    addInspectData.value  = temp
};


const submitInspectForm = async (formEl: FormInstance | undefined) => {
    await validateForm(formEl);
    const params = {
        roadId: addInspectData.value.id,
        dataType:addInspectData.value.dataType
    }
    let loading = ElLoading.service({
        lock: true,
        text: '处理中...',
    });
    try {

        const url = await exportInspectData(params)
        await handleExport(url)
        addInspectShow.value = false;
    } finally {
        loading.close();
    }
};



onMounted(async () => {
    await getProject();
    getList();
});
const { maxTableHeight, setTableMaxHeight } = useTableSetting({ id: 'userTable', offsetBottom: 92 });
</script>

<style scoped lang="scss">
.upload-demo{
    margin-right: 12px;
    display: inline-block;
}
.main-content > .btns{
    margin:10px 0 20px;
}
.search-form{
   ::v-deep(){
    .el-input,.el-select{
        width: 265px !important;
    }
   }
}
.el-button + .upload-demo {
    margin-left: 12px;
}
</style>

